package com.example.yqand4v1_1.service;


import com.example.yqand4v1_1.dao.NewsCollectMapper;
import com.example.yqand4v1_1.dao.NewsMapper;
import com.example.yqand4v1_1.dto.NewsSearchDTO;
import com.example.yqand4v1_1.dao.entity.News;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class NewsService {

    @Resource
    private NewsMapper newsMapper;

    @Resource
    private NewsCollectMapper newsCollectMapper;

    // 查找新闻
    public List<News> search(NewsSearchDTO searchDTO) {
        return newsMapper.search(searchDTO);
    }

    // 用于收藏新闻列表显示，获取收藏新闻的ids->返回对应新闻列表
    public List<News> getByIds(List<Integer> ids) {
        return newsMapper.getByIds(ids);
    }

    // 新闻详情
    // 事务性 点击数+1与检查收藏必须同时完成否则回滚
    @Transactional(rollbackFor = Exception.class)
    public News getById(int id, int userId) {
        News news = newsMapper.getById(id);
        if (news != null) {
            newsMapper.addClickNum(id);
            news.setCollected(newsCollectMapper.countVolunteerCollect(userId, id) > 0);
        }
        return news;
    }

    // 新闻点赞
    public void like(int id) {
        newsMapper.addLikeNum(id);
    }

    // 新闻评论数
    public void addCommentNum(int id) {
        newsMapper.addCommentNum(id);
    }
}
